#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
VS Code 全局标签页设置脚本
自动配置VS Code全局设置以显示多个标签页
"""

import json
import os
import sys
from pathlib import Path
import platform

def get_vscode_settings_path():
    """获取VS Code全局设置文件路径"""
    system = platform.system()
    
    if system == "Windows":
        # Windows
        appdata = os.environ.get('APPDATA')
        if appdata:
            return Path(appdata) / "Code" / "User" / "settings.json"
        else:
            return Path.home() / "AppData" / "Roaming" / "Code" / "User" / "settings.json"
    
    elif system == "Darwin":
        # macOS
        return Path.home() / "Library" / "Application Support" / "Code" / "User" / "settings.json"
    
    elif system == "Linux":
        # Linux
        return Path.home() / ".config" / "Code" / "User" / "settings.json"
    
    else:
        print(f"❌ 不支持的操作系统: {system}")
        return None

def create_tabs_settings():
    """创建标签页设置配置"""
    return {
        # 标签页显示设置
        "workbench.editor.showTabs": "multiple",
        "workbench.editor.tabSizing": "shrink",
        "workbench.editor.tabSizingFixedMinWidth": 100,
        "workbench.editor.tabSizingFixedMaxWidth": 200,
        "workbench.editor.scrollToSwitchTabs": False,
        "workbench.editor.wrapTabs": False,
        
        # 禁用预览模式（关键设置）
        "workbench.editor.enablePreview": False,
        "workbench.editor.enablePreviewFromQuickOpen": False,
        "workbench.editor.enablePreviewFromCodeNavigation": False,
        
        # 打开编辑器列表
        "explorer.openEditors.visible": 15,
        "explorer.openEditors.dynamicHeight": True,
        
        # 编辑器限制
        "workbench.editor.limit.enabled": False,
        "workbench.editor.limit.value": 8,
        "workbench.editor.limit.perEditorGroup": False,
        
        # 文件设置
        "files.autoSave": "afterDelay",
        "files.autoSaveDelay": 1000,
        "files.encoding": "utf8",
        "files.autoGuessEncoding": True,
        
        # 界面设置
        "window.zoomLevel": 0,
        "editor.fontSize": 14,
        "editor.fontFamily": "Consolas, 'Courier New', monospace"
    }

def backup_settings(settings_path):
    """备份现有设置文件"""
    if settings_path.exists():
        backup_path = settings_path.with_suffix('.json.backup')
        try:
            import shutil
            shutil.copy2(settings_path, backup_path)
            print(f"✓ 已备份现有设置到: {backup_path}")
            return True
        except Exception as e:
            print(f"⚠️ 备份失败: {e}")
            return False
    return True

def merge_settings(existing_settings, new_settings):
    """合并现有设置和新设置"""
    merged = existing_settings.copy()
    
    # 更新标签页相关设置
    for key, value in new_settings.items():
        if key.startswith("workbench.editor") or key.startswith("explorer.openEditors"):
            merged[key] = value
            print(f"  更新: {key} = {value}")
    
    return merged

def setup_global_tabs():
    """设置全局标签页显示"""
    print("🚀 VS Code 全局标签页设置工具")
    print("=" * 50)
    
    # 获取设置文件路径
    settings_path = get_vscode_settings_path()
    if not settings_path:
        return False
    
    print(f"📁 设置文件路径: {settings_path}")
    
    # 检查VS Code是否安装
    if not settings_path.parent.exists():
        print(f"❌ VS Code设置目录不存在: {settings_path.parent}")
        print("请确保已安装VS Code")
        return False
    
    # 创建目录（如果不存在）
    settings_path.parent.mkdir(parents=True, exist_ok=True)
    
    # 备份现有设置
    backup_settings(settings_path)
    
    # 读取现有设置
    existing_settings = {}
    if settings_path.exists():
        try:
            with open(settings_path, 'r', encoding='utf-8') as f:
                existing_settings = json.load(f)
            print(f"✓ 读取现有设置文件")
        except Exception as e:
            print(f"⚠️ 读取现有设置失败: {e}")
            existing_settings = {}
    
    # 创建新设置
    new_settings = create_tabs_settings()
    
    # 合并设置
    final_settings = merge_settings(existing_settings, new_settings)
    
    # 写入设置文件
    try:
        with open(settings_path, 'w', encoding='utf-8') as f:
            json.dump(final_settings, f, indent=4, ensure_ascii=False)
        print(f"✓ 设置已保存到: {settings_path}")
        return True
    except Exception as e:
        print(f"❌ 保存设置失败: {e}")
        return False

def main():
    """主函数"""
    print("VS Code 全局标签页设置工具")
    print("此工具将配置VS Code全局设置以显示多个标签页")
    print()
    
    # 确认操作
    response = input("是否继续设置全局标签页显示？(y/N): ").strip().lower()
    if response not in ['y', 'yes', '是']:
        print("操作已取消")
        return
    
    # 执行设置
    if setup_global_tabs():
        print("\n🎉 设置完成！")
        print("\n📋 下一步操作:")
        print("1. 重启VS Code")
        print("2. 打开多个文件测试标签页显示")
        print("3. 使用 Ctrl+Tab 切换标签页")
        print("\n💡 如果设置不生效，请检查:")
        print("   - VS Code是否已重启")
        print("   - 是否有扩展干扰")
        print("   - 项目级设置是否覆盖了全局设置")
    else:
        print("\n❌ 设置失败，请检查错误信息")

if __name__ == "__main__":
    main()
